<template>
  <page-header-wrapper :title="false">
    <a-card title="工资详情">
      <template #extra>
        <a-tooltip>
          <template #title> 数据导出</template>
          <a-button type="primary" icon="database" @click="handleExpert(queryParam)"></a-button>
        </a-tooltip>
      </template>
      <div class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="48">
            <a-col :md="6" :sm="24">
              <a-form-item label="筛选">
                <a-input v-model="queryParam.queryCondition" allow-clear placeholder="请输入" />
              </a-form-item>
            </a-col>
            <a-col :md="(!advanced && 8) || 24" :sm="24">
              <span
                class="table-page-search-submitButtons"
                :style="(advanced && { float: 'right', overflow: 'hidden' }) || {}"
              >
                <a-button type="primary" :loading="loading" @click="handleSearch(queryParam)">查询</a-button>
                <a-button style="margin-left: 8px" @click="() => (queryParam = {})">重置</a-button>
                <!-- <a @click="toggleAdvanced" style="margin-left: 8px">
                  {{ advanced ? '收起' : '展开' }}
                  <a-icon :type="advanced ? 'up' : 'down'"/>
                </a> -->
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>
      <div class="table-operator">
        <a-button type="primary" @click="handleSetting()">工资设置</a-button>
        <a-button type="primary" @click="refresh()">刷新</a-button>
      </div>

      <a-table
        ref="table"
        size="default"
        rowKey="key"
        :columns="columns"
        :loading="loading"
        :pagination="pagination"
        @change="handleTableChange"
        :data-source="loadData"
        :scroll="{ x: `${columns.length}0%` }"
        :footer="handleFooterShow ?? null"
      >
        <span slot="serial" slot-scope="text, record, index">
          {{ index + 1 }}
        </span>
        <span slot="product" slot-scope="text, record">
          <template>
            {{ record?.phoneWage }}
            <a-tag color="#428bca" @click="orderClick(record)">详情</a-tag>
          </template>
        </span>
        <span slot="operWage" slot-scope="text, record">
          <template>
            {{ record?.operWage }}
            <a-tag color="#428bca" @click="mobileClick(record)">详情</a-tag>
          </template>
        </span>
        <span slot="status" slot-scope="text, record">
          <template v-if="record.empName !== '合计'">
            <a-tag color="#82af6f" v-if="record?.status == 1">已发</a-tag>
            <a-tag color="#d15b47" v-else>未发</a-tag>
          </template>
        </span>
        <span slot="action" slot-scope="text, record">
          <template v-if="record.empName !== '合计'">
            <a-tag color="#428bca" @click="handleEdit(record)" v-if="record?.status == 0">编辑</a-tag>
            <a-tag color="#d15b47" v-else @click="handlecx(record)">撤销</a-tag>
            <a-tag color="#ffb752" v-if="record?.status == 0" @click="handleWage(record)">发工资</a-tag>
            <a-tag color="#d15b47" v-if="record?.status == 0" @click="handledelete(record)">删除</a-tag>
          </template>
        </span>
      </a-table>
    </a-card>
    <create-form
      ref="createModal"
      :visible="visible"
      :loading="confirmLoading"
      :model="mdl"
      @cancel="handleCancel"
      @ok="handleOk"
    />
    <push-form
      ref="pushModal"
      :visible="pushVisible"
      :loading="Loading"
      :model="mdlpush"
      @cancel="handlePushCancel"
      @ok="handlePushOk"
    />
  </page-header-wrapper>
</template>

<script>
import moment from 'moment'
import {
  getEmWagesListUsingPOST,
  revokePayoffUsingGET,
  deleteEmWagesUsingPOST,
  refreshEmWagesUsingPOST,
  updateEmWagesUsingPOST,
  payoffUsingGET,
  exportEmWagesUsingPOST,
} from '@/api/api/yuangongguanli.ts'
import CreateForm from './CreateForm'
import PushForm from './pushWage'
export default {
  name: 'WageDetail',
  components: {
    CreateForm,
    PushForm,
  },
  data() {
    return {
      mdl: null,
      mdlpush: null,
      visible: false,
      pushVisible: false,
      Loading: true,
      value: '',
      confirmLoading: false,
      // 高级搜索 展开/关闭
      advanced: false,
      // 查询参数
      pagination: {},
      queryParam: {
        pageNo: 1,
        pageSize: 10,
        queryCondition: '',
        status: '',
      },
      footerDataSource: [],
      // 表头
      columns: [
        {
          title: '员工',
          width: 120,
          dataIndex: 'empName',
        },
        {
          title: '归属店',
          width: 120,
          dataIndex: 'storeName',
        },
        {
          title: '基本工资',
          width: 120,
          dataIndex: 'basicWages',
        },
        {
          title: '商品提成',
          width: 120,
          dataIndex: 'phoneWage',
          needTotal: true,
          scopedSlots: { customRender: 'product' },
        },
        {
          title: '运营商提成',
          dataIndex: 'operWage',
          width: 120,
          needTotal: true,
          scopedSlots: { customRender: 'operWage' },
        },
        {
          title: '实发工资',
          width: 120,
          dataIndex: 'finalWages',
        },
        {
          title: '备注',
          width: 120,
          dataIndex: 'memo',
        },
        {
          title: '状态',
          width: 120,
          dataIndex: 'status',
          needTotal: true,
          scopedSlots: { customRender: 'status' },
        },
        {
          title: '操作',
          dataIndex: 'action',
          width: '200px',
          scopedSlots: { customRender: 'action' },
        },
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: [],
      loading: false,
    }
  },
  created() {
    this.handleSearch(this.queryParam)
  },
  methods: {
    handleExpert(params) {
      exportEmWagesUsingPOST({ ...params, wageMonth: this.$route.params.id }).then((res) => {
        const blob = new Blob([res], {
          type: 'application/vnd.ms-excel;charset=utf-8',
        })
        const filename = '工资列表' + '.xlsx'
        // 将blob对象转为一个URL
        var blobURL = window.URL.createObjectURL(blob)
        // 创建一个a标签
        var tempLink = document.createElement('a')
        // 隐藏a标签
        tempLink.style.display = 'none'
        // 设置a标签的href属性为blob对象转化的URL
        tempLink.href = blobURL
        // 给a标签添加下载属性
        tempLink.setAttribute('download', filename)
        if (typeof tempLink.download === 'undefined') {
          tempLink.setAttribute('target', '_blank')
        }
        // 将a标签添加到body当中
        document.body.appendChild(tempLink)
        // 启动下载
        tempLink.click()
        // 下载完毕删除a标签
        document.body.removeChild(tempLink)
        window.URL.revokeObjectURL(blobURL)
        this.$message.success('导出成功~')
      })
    },
    handleFooterShow() {
      if (this.footerDataSource.length > 0) {
        return (
          <a-table
            ref="table"
            size="default"
            rowKey={Math.random}
            pagination={false}
            columns={this.columns}
            dataSource={this.footerDataSource}
            showHeader={false}
            class="j-table-force-nowrap"
          ></a-table>
        )
      }
    },
    handleSetting() {
      this.$router.push({ path: `/user/wagesetting` })
    },
    handlePushCancel() {
      this.pushVisible = false
      const form = this.$refs.pushModal.form
      form.resetFields() // 清理表单数据（可不做）
    },
    handlePushOk() {
      this.pushVisible = false
      this.Loading = true
      const form = this.$refs.pushModal.form
      form.validateFields((errors, values) => {
        if (!errors) {
          payoffUsingGET({ ...values, emWagesId: values?.id, payOffDate: values?.payOffDate })
            .then((res) => {
              this.handleSearch(this.queryParam)
              this.Loading = false
              this.$message.success('操作成功')
            })
            .catch((error) => {
              this.Loading = false
              this.$message.error(((error.response || {}).data || {}).msg || '请求出现错误')
            })
        } else {
          this.Loading = false
        }
      })
    },

    handleWage(record) {
      this.pushVisible = true
      this.Loading = false
      this.mdlpush = record
    },
    refresh() {
      const that = this
      that.$confirm({
        title: '你确定要刷新工资吗？',
        content: '刷新工资将自动加入工资表中缺少的员工，并更新归属店',
        okText: '确认',
        okType: 'danger',
        cancelText: '取消',
        onOk() {
          refreshEmWagesUsingPOST({ wageMonth: that.$route.params.id })
            .then(() => {
              that.handleSearch(that.queryParam)
              that.$message.success('操作成功')
            })
            .catch((error) => {
              that.$message.error(((error.response || {}).data || {}).msg || '请求出现错误')
            })
        },
      })
    },
    handlecx(record) {
      const that = this
      that.$confirm({
        title: '撤销',
        content: '你确定要撤销发工资操作吗？',
        okText: '确认',
        okType: 'danger',
        cancelText: '取消',
        onOk() {
          revokePayoffUsingGET({ id: record.id })
            .then(() => {
              that.handleSearch(that.queryParam)
              that.$message.success('操作成功')
            })
            .catch((error) => {
              that.$message.error(((error.response || {}).data || {}).msg || '请求出现错误')
            })
        },
      })
    },
    handledelete(record) {
      const that = this
      that.$confirm({
        title: '删除',
        content: '你确定要删除这名员工的工资吗？删除后，将不记录这名员工的工资',
        okText: '确认',
        okType: 'danger',
        cancelText: '取消',
        onOk() {
          deleteEmWagesUsingPOST({ id: record.id })
            .then(() => {
              that.handleSearch(that.queryParam)
              that.$message.success('操作成功')
            })
            .catch((error) => {
              that.$message.error(((error.response || {}).data || {}).msg || '请求出现错误')
            })
        },
      })
    },
    handleSearch(params) {
      this.loading = true
      getEmWagesListUsingPOST({ ...params, wageMonth: this.$route.params.id })
        .then((res) => {
          this.loading = false
          this.loadData = res.data.list.filter((item) => item.id)
          this.footerDataSource = res.data.list
            .filter((item) => !item.id)
            .map((item) => {
              return {
                ...item,
                empName: '合计',
              }
            })
          this.queryParam.pageNo = this.pagination.current
          this.pagination = { ...this.pagination, total: Number(res.data.total) }
        })
        .catch((error) => {
          this.loading = false
          this.$message.error(((error.response || {}).data || {}).msg || '请求出现错误')
        })
    },
    handleTableChange(pagination, filters, sorter) {
      const pager = { ...this.pagination }
      pager.current = pagination.current
      pager.pageSize = pagination.pageSize
      this.pagination = pager
      this.handleSearch({
        sortField: sorter.field,
        sortOrder: sorter.order,
        ...filters,
        pageNo: pagination.current,
        pageSize: pagination.pageSize,
        queryCondition: this.queryParam.queryCondition,
        status: this.queryParam.status,
        date: this.queryParam.date,
      })
    },
    orderClick(record) {
      this.$router.push({ path: `/user/wage/orderGoods/${record?.empId}`, query: { wageMonth: this.$route.params.id } })
    },
    mobileClick(record) {
      this.$router.push({
        path: `/user/wage/orderMobile/${record?.empId}`,
        query: { wageMonth: this.$route.params.id },
      })
    },
    handleEdit(record) {
      this.visible = true
      this.mdl = record
      this.confirmLoading = false
    },
    handleOk() {
      this.visible = false
      this.confirmLoading = true
      const form = this.$refs.createModal.form
      form.validateFields((errors, values) => {
        if (!errors) {
          updateEmWagesUsingPOST({ ...values })
            .then((res) => {
              this.handleSearch(this.queryParam)
              this.confirmLoading = false
              this.$message.success('操作成功')
            })
            .catch((error) => {
              this.confirmLoading = false
              this.$message.error(((error.response || {}).data || {}).msg || '请求出现错误')
            })
        } else {
          this.confirmLoading = false
        }
      })
    },
    handleCancel() {
      this.visible = false
      const form = this.$refs.createModal.form
      form.resetFields() // 清理表单数据（可不做）
    },
    toggleAdvanced() {
      this.advanced = !this.advanced
    },

    resetSearchForm() {
      this.queryParam = {
        date: moment(new Date()),
      }
    },
  },
}
</script>
<style lang="less" scoped>
/deep/ .ant-table-content .ant-table-body {
  position: relative;
  z-index: 2;
  background: #ffffff;
}
/deep/ .ant-table-footer .ant-table-body {
  position: relative !important;
  z-index: 1 !important;
  overflow: hidden !important;
}
/deep/ .ant-table-content > .ant-table-footer {
  position: relative;
  top: -47px;
  z-index: 0;
  padding: 0 !important;
}
</style>
